<script setup lang="ts">
import { useCreate } from '~/pages/writing/hooks'
import { cloneDeep } from 'lodash'
import { chatSendText } from '~/api/chat'
import feedback from '~/utils/feedback'
import { useUserStore } from '~/stores/user'
import { watchThrottled } from '@vueuse/core'
import { ICONFONT } from '~/constants/writing'
const userStore = useUserStore()
const guidedPopupRef = ref()
const { write, report } = await useCreate()

const active = ref('40px')
const { copy } = useCopy()

const copyContent = async (content) => {
    await copy(content)
}
const form = ref([])
const activeModel = ref({})

const handleChangeTab = (_val) => {
    active.value = _val
    activeModel.value =
        _val === '40px' ? cloneDeep(write.value) : cloneDeep(report.value)
    form.value = cloneDeep(activeModel.value.form)
}
handleChangeTab('40px')
const isReceiving = ref(false)
const result = ref('')
let streamReader: ReadableStreamDefaultReader<Uint8Array> | null = null

const contentPost = async () => {
    if (!userStore.isLogin) return userStore.toggleShowLogin(true)
    if (isReceiving.value) return
    const question = form.value.reduce(
        (acc, item) => ({ ...acc, [item.id]: item.props.defaultValue }),
        {}
    )

    result.value = ''
    try {
        isReceiving.value = true
        await chatSendText(
            {
                model: '',
                question,
                type: 2,
                other_id: activeModel.value.id
            },
            {
                onstart(reader) {
                    streamReader = reader
                },
                onmessage(value) {
                    value
                        .trim()
                        .split('data:')
                        .forEach(async (text) => {
                            if (text !== '') {
                                try {
                                    const dataJson = JSON.parse(text)
                                    const { code, event, data } = dataJson
                                    console.log(data)
                                    if (event == 'error' && code === 101) {
                                        guidedPopupRef.value?.open()
                                    } else if (event == 'error') {
                                        feedback.msgError(data)
                                    }

                                    if (data) {
                                        result.value += data
                                    }
                                } catch (error) {}
                            }
                        })
                },
                onclose() {
                    isReceiving.value = false
                }
            }
        )
    } catch (e) {}
}

const resetRadio = () => {
    form.value = cloneDeep(activeModel.value.form)
}

const chatClose = () => {
    streamReader?.cancel()
    isReceiving.value = false
}
watchThrottled(
    result,
    () => {
        nextTick(() => {
            const textarea = document.getElementById('scroll_text')
            textarea.scrollTop = textarea.scrollHeight
        })
    },
    { throttle: 500 }
)
</script>

<template>
    <div class="writing">
        <NuxtLayout name="default">
            <TheGuidedPopup ref="guidedPopupRef" />

            <div class="online-writing-box">
                <div class="tabs pt-16">
                    <div
                        :class="{ 'tab-active': active === '40px' }"
                        @click="handleChangeTab('40px')"
                    >
                        写作
                    </div>
                    <div
                        :class="{ 'tab-active': active === '240px' }"
                        @click="handleChangeTab('240px')"
                    >
                        回复
                    </div>
                </div>
                <div
                    class="flex max-w-[1100px] w-[80%] pt-[70px]"
                    style="margin: 0 auto"
                >
                    <div class="w-[400px]">
                        <div v-for="(i, index) in form" :key="i.id">
                            <template v-if="i.name === 'WidgetRadio'">
                                <div class="mb-6">
                                    <div class="font-bold mb-2 text-[18px]">
                                        <i
                                            class="iconfont"
                                            style="font-size: 18px"
                                            :class="[ICONFONT[i.props.title]]"
                                        />
                                        {{ i.props.title }}
                                    </div>
                                    <el-radio-group
                                        v-model="form[index].props.defaultValue"
                                    >
                                        <el-radio-button
                                            v-for="opt in i.props.options"
                                            :key="opt"
                                            :label="opt"
                                        >
                                            {{ opt }}
                                        </el-radio-button>
                                    </el-radio-group>
                                </div>
                            </template>
                        </div>
                        <div class="clear-btn" @click="resetRadio">清空</div>
                    </div>
                    <div class="flex-1">
                        <div v-for="(i, index) in form" :key="i.id">
                            <template v-if="i.name === 'WidgetTextarea'">
                                <div
                                    class="font-bold text-[18px] mb-1"
                                    style="color: var(--el-color-primary)"
                                >
                                    <i
                                        class="iconfont"
                                        style="font-size: 18px"
                                        :class="[ICONFONT[i.props.title]]"
                                    />
                                    {{ i.props.title }}
                                </div>
                                <el-input
                                    v-model="form[index].props.defaultValue"
                                    type="textarea"
                                    class="mb-4 online-textarea"
                                    :rows="i.props.rows"
                                    :placeholder="i.props.placeholder"
                                />
                            </template>
                        </div>
                        <div v-for="(i, index) in form" :key="i.id">
                            <template v-if="i.name === 'WidgetInput'">
                                <div
                                    class="font-bold text-[18px] mb-1"
                                    style="color: var(--el-color-primary)"
                                >
                                    <i
                                        class="iconfont"
                                        style="font-size: 18px"
                                        :class="[ICONFONT[i.props.title]]"
                                    />
                                    {{ i.props.title }}
                                </div>
                                <el-input
                                    v-model="form[index].props.defaultValue"
                                    type="textarea"
                                    class="mb-4 online-textarea"
                                    :rows="i.props.rows"
                                    :placeholder="i.props.placeholder"
                                />
                            </template>
                        </div>

                        <div>
                            <div class="flex justify-between">
                                <div
                                    class="font-bold text-[18px] mb-1"
                                    style="color: var(--el-color-primary)"
                                >
                                    <i
                                        class="iconfont icon-yulan"
                                        style="font-size: 18px"
                                    />
                                    预览
                                </div>
                                <div class="text-[#838a95] cursor-pointer">
                                    <div
                                        v-if="result"
                                        @click="copyContent(result)"
                                    >
                                        <i class="iconfont icon-copy" />复制
                                    </div>
                                </div>
                            </div>

                            <div class="relative">
                                <el-input
                                    v-model="result"
                                    :rows="14"
                                    id="scroll_text"
                                    class="online-textarea"
                                    type="textarea"
                                    placeholder="生成内容"
                                />
                                <div
                                    v-if="!result && isReceiving"
                                    class="absolute z-1 top-[9px] left-[10px] bg-white flex items-center"
                                >
                                    <div class="is-routing mr-1">
                                        <i
                                            class="iconfont icon-jiazaixiao is-routing"
                                        />
                                    </div>

                                    <span>思考中...</span>
                                </div>
                            </div>
                            <div class="text-center">
                                <el-button
                                    v-if="isReceiving && result"
                                    class="clear-btn w-[130px] text-center"
                                    style="
                                        line-height: 40px;
                                        font-size: 16px;
                                        height: 40px;
                                        margin-top: 24px;
                                    "
                                    @click="chatClose"
                                >
                                    <i
                                        class="iconfont icon-tingzhi mr-1"
                                        style="font-size: 24px"
                                    />
                                    停止生成
                                </el-button>
                            </div>

                            <el-button
                                v-if="!isReceiving"
                                :loading="isReceiving"
                                type="primary"
                                class="w-full text-center"
                                style="
                                    line-height: 40px;
                                    font-size: 16px;
                                    border-radius: 8px;
                                    height: 40px;
                                    margin-top: 24px;
                                "
                                @click="contentPost"
                            >
                                帮我写
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
        </NuxtLayout>
    </div>
</template>

<style scoped lang="scss">
@import 'assets/styles/fix_online_css.scss';

:deep(.el-radio-group label) {
    margin-right: 14px;
    margin-bottom: 10px;
    height: 30px !important;
}
:deep(.el-textarea__inner) {
    border-radius: 8px !important;
    padding: 10px 12px;
}
:deep(.el-radio-button__inner) {
    border: 1px solid #dcdfe6;
    border-radius: 8px !important;
    height: 30px !important;
    padding: 0 16px;
    line-height: 28px !important;

    //border-left: unset;
}
//.radio-btn {
//  font-size: 12px;
//  padding: 5px 11px;
//  background: white;
//  border: 1px solid var(--el-border-color);
//}
.tabs {
    width: 400px;
    display: flex;
    margin: 0 auto;
    font-size: 24px;
    position: relative;
    font-weight: bold;
    color: #999999;
    line-height: 50px;
    transition: 0.5s ease;
    border-bottom: 3px solid #dadada;
    div {
        flex-shrink: 0;
        width: 200px;
        text-align: center;
        cursor: pointer;
    }
    &::before {
        content: '';
        width: 120px;
        height: 3px;
        transition: 0.5s ease;

        background: var(--el-color-primary);
        position: absolute;
        bottom: -2px;
        left: v-bind(active);
    }
}
.tab-active {
    color: #333333;
}
.clear-btn {
    color: var(--el-color-primary);
    border: 1px solid var(--el-color-primary);
    display: inline-block;
    line-height: 30px;
    cursor: pointer;
    padding: 0 16px;
    background: white;
    border-radius: 8px;
    margin-top: 10px;
}

.is-routing {
    animation: rotate 2s infinite linear;
    transform-origin: center center;
    display: inline-block;
}
@keyframes rotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(-360deg);
    }
}
.help-btn {
    &:hover {
        color: white;
        background: linear-gradient(
            90deg,
            var(--el-color-primary) 0%,
            var(--el-color-primary-light-3) 100%
        );
    }
}
</style>
